package com.swust.book_shop.inteceptor;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.swust.book_shop.constant.JWTConstant;
import com.swust.book_shop.pojo.ResultCodeEnum;
import jdk.nashorn.internal.scripts.JS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liushuai
 * @create 2022-05-05 17:15
 */
@Slf4j
public class JWTInteceptor  implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //在拦截器中设置允许跨域
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Headers","*");
//        response.setHeader("Access-Control-Allow-Methods","*");
//        response.setHeader("Access-Control-Allow-Credentials","true");
//        response.setHeader("Access-Control-Max-Age","3600");
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            System.out.println("Method:OPTIONS");
            return true;
        }
        String header = request.getHeader(JWTConstant.AUTH_HEADER);
        System.out.println(header);
        log.info("请求携带的token:{}",header);
        Map<String,Object> map = new HashMap<>(5);
        map.put("message","未携带token");
        if(StringUtils.hasText(header)){
            try {
                boolean verify = JWTUtil.verify(header, JWTConstant.SECERT.getBytes(StandardCharsets.UTF_8));
                return verify;
            } catch (Exception e) {
                map.put("message",e.getMessage());
            }
        }
        map.put("code",203);
        String s = JSONUtil.toJsonStr(map);
        String s1 = JSONUtil.toJsonPrettyStr(s);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(s1);
        log.info("被拦截了");
        return false;


    }
}
